#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

class SQLParser:
    def __init__(self, sql):
        self.sql = sql
        self.n = len(sql)
        self.i = 0
        self.statements = []
        self.current = []
        self.state = None

    def _add_statement(self):
        """将当前语句添加到结果列表"""
        if self.current:
            statement = ''.join(self.current).strip()
            if statement:
                self.statements.append(statement)
            self.current = []

    def _handle_block_comment(self):
        """处理块注释 /* ... */"""
        end = self.sql.find('*/', self.i)
        if end == -1:
            self.i = self.n
        else:
            self.i = end + 2
        self.state = None

    def _handle_line_comment(self):
        """处理行注释 -- ..."""
        end = self.sql.find('\n', self.i)
        self.i = end if end != -1 else self.n
        self.state = None

    def _handle_quote(self):
        """主入口：处理单引号字符串"""
        self._append_char_and_advance()
        while self.i < self.n:
            char = self.sql[self.i]
            if char == "'":
                self._process_quote_end()
                break
            self._append_char_and_advance()
        self.state = None

    def _process_quote_end(self):
        """处理单引号结尾（可能含转义）"""
        self._append_char_and_advance()
        self._handle_escaped_quotes()

    def _handle_escaped_quotes(self):
        """处理转义单引号序列（如 ''）"""
        while self.i < self.n and self.sql[self.i] == "'":
            self._append_char_and_advance()

    def _append_char_and_advance(self):
        """通用操作：添加当前字符并移动指针"""
        self.current.append(self.sql[self.i])
        self.i += 1

    def _handle_normal(self):
        """普通字符处理"""
        char = self.sql[self.i]
        if char == '/' and self.i + 1 < self.n and self.sql[self.i + 1] == '*':
            self.state = 'block'
            self.i += 2
        elif char == '-' and self.i + 1 < self.n and self.sql[self.i + 1] == '-':
            self.state = 'line'
            self.i += 2
        elif char == "'":
            self.current.append(char)
            self.i += 1
            self.state = 'quote'
        elif char == ';':
            self._add_statement()
            self.i += 1
        else:
            self.current.append(char)
            self.i += 1

    def split(self):
        """主解析方法"""
        while self.i < self.n:
            if self.state == 'block':
                self._handle_block_comment()
            elif self.state == 'line':
                self._handle_line_comment()
            elif self.state == 'quote':
                self._handle_quote()
            else:
                self._handle_normal()
        self._add_statement()
        return self.statements


def split_sql_statements(sql):
    split_sql = SQLParser(sql).split()
    return [item + ";" for item in split_sql]
